package cn.aopmin.java.api.lang;

/**
 * 使用同步代码块解决线程安全问题
 * @author 白豆五
 * @since 2025/1/29
 */
public class synchronizedBlockedTest {
    public static void main(String[] args) {
        // 创建售票任务对象
        TicketWindow2 ticketWindow = new TicketWindow2();

        // 模拟4个窗口
        Thread window1 = new Thread(ticketWindow, "窗口1：");
        Thread window2 = new Thread(ticketWindow, "窗口2：");
        Thread window3 = new Thread(ticketWindow, "窗口3：");
        Thread window4 = new Thread(ticketWindow, "窗口4：");

        window1.start();
        window2.start();
        window3.start();
        window4.start();
    }
}

/**
 * 售票任务
 */
class TicketWindow2 implements Runnable {
    private final Object lock = new Object();

    /**
     *  100张票，共享变量， 由4个线程共享
     */
    int ticket = 100;

    /**
     * 售票, 没有考虑线程安全问题
     */
    @Override
    public void run() {
        // synchronized (this) { //this表示当前对象
        while (true) {
            synchronized (lock) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String msg = String.format("%s正在出售第%s张票", Thread.currentThread().getName(), ticket);
                    System.out.println(msg);
                    ticket--;
                    lock.notifyAll();
                } else {
                    lock.notifyAll();
                    break;
                }
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
